package com.xiaobo.framework.kits;



import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaobo.framework.common.exception.BizException;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: <a href="get_xiaobo@163.com">Josh_Xu</a>
 * @description:
 * @create: 2019-10-22 01:19
 **/
public class PageKits {

    private static final int currentPage = 1;
    private static final int pageSize = 20;

    public PageKits() {
    }

    public static <T> List<T> startPage(Integer currentPage, Integer pageSize, Integer count, List<T> list){
        if (currentPage==null){
            currentPage = PageKits.currentPage;
        }
        if (pageSize==null){
            pageSize = PageKits.pageSize;
        }

        int start = (currentPage - 1) * pageSize;
        int pages = (int) Math.ceil((count * 1.0) / pageSize);
        return list.stream().skip(start).limit(pageSize).collect(Collectors.toList());
    }

    public static <T> Page<T> startPage_MybatisPlus(Integer currentPage,Integer pageSize,Integer count,List<T> list){
        if (currentPage==null){
            currentPage = PageKits.currentPage;
        }
        if (pageSize==null){
            pageSize = PageKits.pageSize;
        }

        int start = (currentPage - 1) * pageSize;
        int pages = (int) Math.ceil((count * 1.0) / pageSize);

        List<T> lists = list.stream().skip(start).limit(pageSize).collect(Collectors.toList());
        Page<T> page = new Page<>();
        page.setPages(pages);
        page.setTotal(count);
        page.setCurrent(currentPage);
        page.setSize(pageSize);
        page.setRecords(lists);
        return page;
    }

    public static void checkPageParam_Exception(Integer currentPage,Integer pageSize) throws BizException {
        if (currentPage==null || currentPage<=0 || pageSize==null|| pageSize<=0){
            throw new BizException("无效的当前页或每页条数!");
        }
    }

    public static int compute(Integer currentPage,Integer pageSize,Integer count,ComputeType computeType){
        if (computeType.equals(ComputeType.START_INDEX)){
            return (currentPage - 1) * pageSize;
        }
        if (computeType.equals(ComputeType.PAGES)){
            return (int) Math.ceil((count * 1.0) / pageSize);
        }
        throw new BizException("计算类型错误!");
    }

    public enum ComputeType{
        START_INDEX,PAGES;
    }
}
